﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using _80X_CG_Frame.Objects;
using _80X_CG_Frame.Workers;
using MahApps.Metro.Controls;
using Newtonsoft.Json.Linq;
using FolderBrowserDialog = System.Windows.Forms.FolderBrowserDialog;
using OpenFileDialog = System.Windows.Forms.OpenFileDialog;

namespace _80X_CG_Frame.Windows
{
    /// <summary>
    /// Interaction logic for Config.xaml
    /// </summary>
    public partial class Config : MetroWindow
    {
        bool close_flag = false;
        private  JObject user_info;
        private List<TextBox> config_textboxs = new List<TextBox>();
        private List<ComboBox> config_comboboxes = new List<ComboBox>();
        //连接地址字典
        private Dictionary<string, string> address_dic = new Dictionary<string, string>();
        //PLC寄存器字典
        private Dictionary<string, string> register_dic = new Dictionary<string, string>();
        //SFC参数字典
        private Dictionary<string, string> SFC_param_dic = new Dictionary<string, string>();
        //SFC 上料确认Demo
        private JObject SFC_上料确认Demo;
        //SFC 过站签收Demo
        private JObject SFC_过站Demo;
        //SFC 绑码Demo
        private JObject SFC_绑码Demo;
        //SFC 参数上传Demo
        private JObject SFC_参数上传Demo;
        public Config()
        {
            InitializeComponent();
            AddConrtrols();
            LoadConfigs();
        }

        private void LoadConfigs()
        {
            foreach (TextBox tb in config_textboxs)
            {
                tb.Text = GLOBAL.config.Get(tb.Name);
            }
            foreach (ComboBox cb in config_comboboxes)
            {
                cb.SelectedIndex = cb.Items.IndexOf(GLOBAL.config.Get(cb.Name));
            }
            foreach(var item in address_name.Items)
            {
                address_dic[(string)item] = GLOBAL.config.Get((string)item + "_address");
            }
            address_name.SelectedIndex = 0;
            foreach (var item in register_notes.Items)
            {
                register_dic[(string)item] = GLOBAL.config.Get((string)item + "_register");
            }
            register_notes.SelectedIndex = 0;
            foreach (var item in SFC_param_name.Items)
            {
                SFC_param_dic[(string)item] = GLOBAL.config.Get((string)item + "_param");
            }
            SFC_param_name.SelectedIndex = 0;


            SFC_上料确认Demo = GLOBAL.config.configs["SFC_上料确认demo"] as JObject;
            SFC_上料确认Demo_name.Items.Clear();
            //自动加载并添加到下拉框
            foreach (var t in SFC_上料确认Demo)
            {
                SFC_上料确认Demo_name.Items.Add(t.Key);
            }
            SFC_上料确认Demo_name.SelectedIndex = 0;

            SFC_过站Demo = GLOBAL.config.configs["SFC_过站demo"] as JObject;
            SFC_过站Demo_name.Items.Clear();
            //自动加载并添加到下拉框
            foreach (var t in SFC_过站Demo)
            {
                SFC_过站Demo_name.Items.Add(t.Key);
            }
            SFC_过站Demo_name.SelectedIndex = 0;


            SFC_绑码Demo = GLOBAL.config.configs["SFC_绑码demo"] as JObject;
            SFC_绑码Demo_name.Items.Clear();
            //自动加载并添加到下拉框
            foreach (var t in SFC_绑码Demo)
            {
                SFC_绑码Demo_name.Items.Add(t.Key);
            }
            SFC_绑码Demo_name.SelectedIndex = 0;

            SFC_参数上传Demo = GLOBAL.config.configs["SFC_参数上传demo"] as JObject;
            SFC_参数上传Demo_name.Items.Clear();
            //自动加载并添加到下拉框
            foreach (var t in SFC_参数上传Demo)
            {
                SFC_参数上传Demo_name.Items.Add(t.Key);
            }
            SFC_参数上传Demo_name.SelectedIndex = 0;
            
            var ui = GLOBAL.config.configs["user_info"];
            user_info = JObject.Parse(Login.DecryptJson((string)ui));
            uerName_cb.Items.Clear();
            foreach (var t in user_info)
            {
                uerName_cb.Items.Add(t.Key);
            }
            if (uerName_cb.Items.Count != 0)
                uerName_cb.SelectedIndex = 0;

            if (GLOBAL.user.R == Objects.Right.Operator)
            {
                read_config_button.IsEnabled = false;
                save_button.IsEnabled = false;
                cancel_button.IsEnabled = false;
                reset_button.IsEnabled = false;

                login_button.Visibility = Visibility.Visible;
                logout_button.Visibility = Visibility.Hidden;
            }
            else
            {
                login_button.Visibility = Visibility.Hidden;
                logout_button.Visibility = Visibility.Visible;
            }
            Log.Write("读取配置成功");
        }

        private void AddConrtrols()
        {
            //文本框控件添加处,自动更新
            config_textboxs.Add(log_folder_path);
            config_textboxs.Add(history_data_folder);
            config_textboxs.Add(log_zip_period);
            config_textboxs.Add(SFC_cache_days);
            config_textboxs.Add(SFC_upload_period);
            //config_textboxs.Add(luomu_position1);
            //config_textboxs.Add(luomu_position2);
            //config_textboxs.Add(pingbipian_position);
            config_textboxs.Add(机台号);
            config_textboxs.Add(螺母焊接机台编号);
            config_textboxs.Add(屏蔽片焊接机台编号);
            config_textboxs.Add(camera_process_path);
            //下拉框控件添加
            config_comboboxes.Add(auto_start);
            config_comboboxes.Add(机台类型);
            config_comboboxes.Add(机器人类型);
            config_comboboxes.Add(SFC_enable);
            config_comboboxes.Add(扫码_enable);
            config_comboboxes.Add(PLC类型);
            config_comboboxes.Add(螺母w1轴线接反);
            config_comboboxes.Add(螺母w2轴线接反);
            config_comboboxes.Add(屏蔽片w轴线接反);
            //自动加载并添加到下拉框
            GLOBAL.config.configs["PLC_registers"].ToList().ForEach(t => register_dic[(string)t] = "");
            foreach(var t in register_dic.Keys)
            {
                register_notes.Items.Add(t);
            }
            //自动加载并添加到下拉框
            GLOBAL.config.configs["SFC_params"].ToList().ForEach(t => SFC_param_dic[(string)t] = "");
            foreach (var t in SFC_param_dic.Keys)
            {
                SFC_param_name.Items.Add(t);
            }
        }
        private void SaveConfigs()
        {
            foreach (TextBox tb in config_textboxs)
            {
                GLOBAL.config.Set(tb.Name, tb.Text);
            }
            foreach (ComboBox cb in config_comboboxes)
            {
                GLOBAL.config.Set(cb.Name, (string)(cb.SelectedItem));
            }
            foreach (var item in address_name.Items)
            {
                GLOBAL.config.Set((string)item + "_address", address_dic[(string)item]);
            }
            foreach (var item in register_notes.Items)
            {
                GLOBAL.config.Set((string)item + "_register", register_dic[(string)item]);
            }
            foreach (var item in SFC_param_name.Items)
            {
                GLOBAL.config.Set((string)item + "_param", SFC_param_dic[(string)item]);
            }

            GLOBAL.config.configs["SFC_上料确认demo"] = SFC_上料确认Demo;
            GLOBAL.config.configs["SFC_过站demo"] = SFC_过站Demo;
            GLOBAL.config.configs["SFC_绑码demo"] = SFC_绑码Demo;
            GLOBAL.config.configs["SFC_参数上传demo"] = SFC_参数上传Demo;
            GLOBAL.sfc.更新地址(GLOBAL.config.Get("过站报告_param"), GLOBAL.config.Get("上料验证_param"), GLOBAL.config.Get("焊接参数_param"));
            GLOBAL.config.WriteConfig();
        }

        private void logs_folder_browse_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.Description = "请选择日志文件夹";
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(fbd.SelectedPath))
                {
                    System.Windows.MessageBox.Show(this, "文件夹路径不能为空!", "提示");
                    return;
                }
                this.log_folder_path.Text = fbd.SelectedPath;
            }
        }

        private void open_log_folder_Click(object sender, RoutedEventArgs e) => System.Diagnostics.Process.Start("Explorer", this.log_folder_path.Text);

        private void history_data_folder_browse_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.Description = "请选择历史数据文件夹";
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(fbd.SelectedPath))
                {
                    System.Windows.MessageBox.Show(this, "文件夹路径不能为空!", "提示");
                    return;
                }
                this.history_data_folder.Text = fbd.SelectedPath;
            }
        }

        private void open_history_data_folder_Click(object sender, RoutedEventArgs e) => System.Diagnostics.Process.Start("Explorer", history_data_folder.Text);

        private void reset_button_Click(object sender, RoutedEventArgs e) => LoadConfigs();

        private void save_button_Click(object sender, RoutedEventArgs e) => SaveConfigs();

        private void cancel_button_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.Hide();
            if (!close_flag)
                e.Cancel = true;
        }
        public void RealClose()
        {
            close_flag = true;
            this.Close();
        }

        private void address_change_Click(object sender, RoutedEventArgs e) => address_dic[(string)address_name.SelectedItem] = address.Text;

        private void address_name_SelectionChanged(object sender, SelectionChangedEventArgs e) => address.Text = address_dic[(string)address_name.SelectedItem];

        private void register_address_change_Click(object sender, RoutedEventArgs e) => register_dic[(string)register_notes.SelectedItem] = register_address.Text;

        private void register_notes_SelectionChanged(object sender, SelectionChangedEventArgs e) => register_address.Text = register_dic[(string)register_notes.SelectedItem];
        

        private void read_config_button_Click(object sender, RoutedEventArgs e)
        {
            GLOBAL.config.ReadConfig();
            GLOBAL.sfc.更新地址(GLOBAL.config.Get("过站报告_param"), GLOBAL.config.Get("上料验证_param"), GLOBAL.config.Get("焊接参数_param"));
            LoadConfigs();
        }

        private void camera_process_path_browse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fbd = new OpenFileDialog();
            fbd.Title = "请选择视觉后台程序";
            fbd.CheckFileExists = true;
            fbd.CheckPathExists = true;
            fbd.Multiselect = false;
            fbd.FileName = "SmartCAM.exe";
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(fbd.FileName))
                {
                    System.Windows.MessageBox.Show(this, "文件路径不能为空!", "提示");
                    return;
                }
                this.camera_process_path.Text = fbd.FileName;
            }
        }

        private void SFC_param_change_Click(object sender, RoutedEventArgs e)
        {
            SFC_param_dic[(string)SFC_param_name.SelectedItem] = SFC_param.Text;
        }

        private void SFC_param_name_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SFC_param.Text = SFC_param_dic[(string)SFC_param_name.SelectedItem];
        }

        private void SFC_Demo_name_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(SFC_上料确认Demo_name.SelectedItem != null)
                SFC_Demo_value.Text = SFC_上料确认Demo[SFC_上料确认Demo_name.SelectedItem as string].ToString();
        }

        private void SFC_Demo_change_Click(object sender, RoutedEventArgs e)
        {
            SFC_上料确认Demo[SFC_上料确认Demo_name.SelectedItem as string] = JToken.Parse(SFC_Demo_value.Text);
        }

        private void SFC_过站Demo_name_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(SFC_过站Demo_name.SelectedItem != null)
                SFC_过站Demo_value.Text = SFC_过站Demo[SFC_过站Demo_name.SelectedItem as string].ToString();
        }

        private void SFC_过站Demo_change_Click(object sender, RoutedEventArgs e)
        {
            SFC_过站Demo[SFC_过站Demo_name.SelectedItem as string] = JToken.Parse(SFC_过站Demo_value.Text);
        }

        private void login_button_Click(object sender, RoutedEventArgs e)
        {
            Login login = new Login();
            login.ShowDialog();
            if (login.DialogResult.Value&& GLOBAL.user.R == Objects.Right.Admin)
            {
                read_config_button.IsEnabled = true;
                save_button.IsEnabled = true;
                cancel_button.IsEnabled = true;
                reset_button.IsEnabled = true;
                login_button.Visibility = Visibility.Hidden;
                logout_button.Visibility = Visibility.Visible;

            }
        }

        private void logout_button_Click(object sender, RoutedEventArgs e)
        {
            GLOBAL.user.R = Objects.Right.Operator;
            read_config_button.IsEnabled = false;
            save_button.IsEnabled = false;
            cancel_button.IsEnabled = false;
            reset_button.IsEnabled = false;
            login_button.Visibility = Visibility.Visible;
            logout_button.Visibility = Visibility.Hidden;
        }

        private void modify_btn_Click(object sender, RoutedEventArgs e)
        {
            var user = user_info[(string)uerName_cb.SelectedItem];
            if (user != null)
            {
                var confirm = false;
                var user_right = User.GetRight((string)user["right"]);
                //直接更改非管理员密码不需确认旧密码
                if (user_right != Right.Admin)
                    confirm = true;
                else
                    confirm = Login.Vertify(old_password.Password, (string)user["password"]);
                if (confirm)
                {
                    if(new_password.Password != renew_password.Password)
                    {
                        password_warn_msg.Text = "新密码与确认密码不一致";
                    }
                    else
                    {
                        user["password"] = Login.Encrypt(new_password.Password);
                        user_info[(string)uerName_cb.SelectedItem] = user;
                        GLOBAL.config.configs["user_info"] = Login.EncryptJson(user_info.ToString());
                        password_warn_msg.Text = "";
                        //仍然需要点击保存
                        //GLOBAL.config.WriteConfig();
                    }
                }
                else
                {
                    password_warn_msg.Text = "旧密码错误";
                }
            }
        }

        private void SFC_绑码Demo_name_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (SFC_绑码Demo_name.SelectedItem != null)
                SFC_绑码Demo_value.Text = SFC_绑码Demo[SFC_绑码Demo_name.SelectedItem as string].ToString();
        }

        private void SFC_绑码Demo_change_Click(object sender, RoutedEventArgs e)
        {
            SFC_绑码Demo[SFC_绑码Demo_name.SelectedItem as string] = JToken.Parse(SFC_绑码Demo_value.Text);
        }

        private void SFC_参数上传Demo_change_Click(object sender, RoutedEventArgs e)
        {
            SFC_参数上传Demo[SFC_参数上传Demo_name.SelectedItem as string] = JToken.Parse(SFC_参数上传Demo_value.Text);
        }

        private void SFC_参数上传Demo_name_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (SFC_参数上传Demo_name.SelectedItem != null)
                SFC_参数上传Demo_value.Text = SFC_参数上传Demo[SFC_参数上传Demo_name.SelectedItem as string].ToString();
        }
    }
}
